//
//  SWListLayer.m
//  BeautyGuessFree
//
//  Created by Charles How on 12-4-11.
//  Copyright 2012年 hust. All rights reserved.
//

#import "SWListLayer.h"

#import "storage.h"
#import "GameMusicSetting.h"

@implementation SWListLayer

@synthesize adController;

@synthesize mPageIndex;
@synthesize mPageCount;

-(id) init
{
	if( (self=[super init]) ) {
		
		
        
		//init array
		menuItemArray=[[NSMutableArray alloc] init];
		
		CGSize s = [[CCDirector sharedDirector] winSize];
		
		//bg
		CCSprite * bg=[CCSprite spriteWithFile:@"sw-list-bg.png"];
		bg.position=ccp(s.width/2,s.height/2);
        
        float scaleX=1.0,scaleY=1.0;
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            scaleX=s.width/(float)bg.contentSize.width;
            scaleY=s.height/(float)bg.contentSize.height;
        }
        else{
            scaleX=1.0;
            scaleY=1.0;
        }
        
        bg.scaleX=scaleX;
        bg.scaleY=scaleY;
        
		[self addChild:bg z:0 tag:100];
		
        
        /*
		//board
		
		CCSprite * board=[CCSprite spriteWithFile:@"button_other_003.png"];
		board.position=ccp(s.width/2,s.height/2);
		[self addChild:board];
		
		//////title
        
		CCLabel *title = [CCLabel labelWithString:@"Welcome to software Garden"  
                                         fontName:@"Marker Felt" 
                                         fontSize:20];
		title.position = ccp(s.width/2-s.width/20, s.height-50);
		[self addChild:title];
		
		id jump = [CCJumpBy actionWithDuration:3 position:ccp(s.width/20*2,0) height:0 jumps:4];
		[title runAction: [CCRepeatForever actionWithAction:
						   [CCSequence actions: jump, [jump reverse], nil]
						   ]
		 ];
		*/
        
		
		/////////
		/*
         CCLabelTTF *label = [CCLabelTTF labelWithString:@"get 1000 coins " 
         fontName:@"Marker Felt" 
         fontSize:24];
         CCMenuItemLabel *item1 = [CCMenuItemLabel itemWithLabel:label 
         target:self 
         selector:@selector(menuCallback1:)];
         */
        
        
        
		///////iap menus begin
		//[CCMenuItemFont setFontName: @"Marker Felt"];
		//[CCMenuItemFont setFontSize:25];
		
        

		
        /*
        //获取软件列表
        SWList * aSWList=[SWList sharedInstance];
        SW_ITEM * item=[aSWList getItemByIndex:0];
        
        ////将NSData中图象数据转换位精灵图象
        UIImage* image=[UIImage imageWithData:item.imageData];
        
        
        int oriW=image.size.width;
        int oriH=image.size.height;
        float scale=board.contentSize.width/2.5/oriW;
        
        //UIImage* imageSmall=[self scaleAndRotateImage:image xScale:0.5 yScale:0.5];
        UIImage* image2=[self resizeImage:image andScaleX:scale andScaleY:scale];
        CCSprite* spt=[CCSprite spriteWithCGImage:image2.CGImage key:@"SW_ITEM_PIC"];
        
        */
        NSString * path=[storage dataFilePathInResource:@"sw-list-board.png"];
        UIImage* image=[UIImage imageWithContentsOfFile:path];
        float scale=s.width/MAX_COLS/image.size.width;
		UIImage* image2=[self resizeImage:image andScaleX:scale andScaleY:scale];
        

        
        
        for (int i=0; i<MAX_ROWS*MAX_COLS; i++) {
            CCSprite* board=[CCSprite spriteWithCGImage:image2.CGImage key:@"BOARD_PIC"];
            CCSprite* board2=[CCSprite spriteWithCGImage:image2.CGImage key:@"BOARD_PIC_H"];
            board2.color=ccc3(255, 255, 0);
            
            CCMenuItemSprite *item1 = [CCMenuItemSprite itemFromNormalSprite:board
                                                              selectedSprite:board2
                                                                      target:self selector:@selector(menuCallback_Link:)];
            //item1.color=ccc3(255, 0, 0);
            
            /*
            CCMenuItemFont *item2 = [CCMenuItemFont itemFromString: item.name 
                                                            target:self selector:@selector(menuCallback_Link:)];
            item2.color=ccc3(0, 255, 0);
            */
            
            [menuItemArray addObject:item1];  //index 0
        }

		//[menuItemArray addObject:item2];  //index 1
        
		
		assert([menuItemArray count] <= MAX_ROWS*MAX_COLS);
		
		menu = [CCMenu menuWithItems:
						[menuItemArray objectAtIndex:0], 
						[menuItemArray objectAtIndex:1],
                        [menuItemArray objectAtIndex:2], 
						[menuItemArray objectAtIndex:3],
                        [menuItemArray objectAtIndex:4], 
						[menuItemArray objectAtIndex:5],
						nil]; // 4 items.
		
		//[menu alignItemsVertically];
		
         [menu alignItemsInColumns:
		 [NSNumber numberWithUnsignedInt:MAX_COLS],
		 [NSNumber numberWithUnsignedInt:MAX_COLS],
		 //[NSNumber numberWithUnsignedInt:1],
		 //[NSNumber numberWithUnsignedInt:1],
		 
		 nil
		 ]; 
         
		
        
		
        
        
		
        
		id spin1 = [CCRotateBy actionWithDuration:3 angle:360];
		id spin2 = [[spin1 copy] autorelease];
		id spin3 = [[spin1 copy] autorelease];
		
		//[item1 runAction: [CCRepeatForever actionWithAction:spin1]];
		//[item2 runAction: [CCRepeatForever actionWithAction:spin2]];
		//[item3 runAction: [CCRepeatForever actionWithAction:spin3]];
        
        //menu.anchorPoint=ccp(0.0,0.0);
		menu.position=ccp(menu.contentSize.width/2
                          , s.height-menu.contentSize.height/2);
        int width=menu.contentSize.width;
        int height=menu.contentSize.height;
		[self addChild:menu z:1 tag:SWListLayer_ENUM_TAG_MENU];

        int i=0;
		for( CCNode *child in [menu children] ) {
			
			///修正某些菜单的位置
            child.position=ccp(child.position.x-20,child.position.y);

            if (i>=0 && i<=2) {
                child.position=ccp(child.position.x,child.position.y+12);
            }
            else if (i>=3 && i<=5) {
                child.position=ccp(child.position.x,child.position.y+40);
            }
            
			i++;
		}
        
        
		// Image Item  ,back button
		CCSprite * tmpSprite=[CCSprite spriteWithFile:@"sw-list-quit0.png"];
		CGSize winSize=[[CCDirector sharedDirector] winSize];
		back = [CCMenuItemImage 
                itemFromNormalImage:@"sw-list-quit0.png" 
                selectedImage:@"sw-list-quit1.png" 
                target:self 
                selector:@selector(backCallback:)];
		CCMenu *menuBack = [CCMenu menuWithItems:
							back,nil];
		[menuBack alignItemsHorizontally];
		menuBack.position=ccp(winSize.width-tmpSprite.contentSize.width/2,tmpSprite.contentSize.height/2); ///右下角
		[self addChild: menuBack z:5 tag:SWListLayer_ENUM_TAG_BACK];
		
		
        
        //ad bg
        CCSprite * ad_bg=[CCSprite spriteWithFile:@"sw-list-ad-bg.png"];
        ad_bg.position=ccp(s.width/2,ad_bg.contentSize.height/2);
        [self addChild:ad_bg z:0 tag:1001];
        ad_bg.visible=false;
        
        
        
        [self addButtons];
        [self getPageCount];
	}
	
	return self;
}

-(void)addButtons
{
    /*
    CGSize size=[[CCDirector sharedDirector] winSize];
    CCSprite * arrow_up=[CCSprite spriteWithFile:@"arrow_green.png"];
    arrow_up.position=ccp(size.width-arrow_up.contentSize.width/2
                          , size.height-arrow_up.contentSize.height/2);
    [self addChild:arrow_up];
     */
    
    
    // Image Item  ,up button
    CCSprite * tmpSprite=[CCSprite spriteWithFile:@"arrow_green.png"];
    CGSize winSize=[[CCDirector sharedDirector] winSize];
    CCMenuItemImage * up_button = [CCMenuItemImage 
            itemFromNormalImage:@"arrow_green.png" 
            selectedImage:@"arrow_green2.png" 
            target:self 
            selector:@selector(upCallback:)];
    
    CCMenuItemImage * down_button = [CCMenuItemImage 
                                   itemFromNormalImage:@"arrow_red.png" 
                                   selectedImage:@"arrow_red2.png" 
                                   target:self 
                                   selector:@selector(downCallback:)];
    
    
    CCMenu *menu = [CCMenu menuWithItems:
                        up_button,down_button,nil];
    
    [menu alignItemsVerticallyWithPadding:70.0];
    menu.position=ccp(winSize.width-tmpSprite.contentSize.width/2,menu.position.y+tmpSprite.contentSize.height/2); 
    [self addChild: menu z:5 ];
}



-(int)getPageCount
{
    SWList * aSWList=[SWList sharedInstance];
    int count=[aSWList getSWCount];
    mPageCount=(count+MAX_COUNT_PER_PAGE-1)/(MAX_COUNT_PER_PAGE);
}

-(void)setPageIndex:(int)index
{
    if (mPageCount == 0) {
        mPageIndex=0;
        return;
    }
    
    
    assert(index >=0 && index <mPageCount);
    
    mPageIndex=index;
}

-(void)updateDisplay
{
    
    if (mPageCount == 0) {
        return;
    }
    
    for (int i=0; i<MAX_COUNT_PER_PAGE; i++) {
        //清除上次显示的内容
        if ([self getChildByTag:SPR_TAG_PIC_START+i] != nil) {
            [self removeChildByTag:SPR_TAG_PIC_START+i cleanup:YES];
        }
        
        if ([self getChildByTag:SPR_TAG_LAB_START+i] != nil) {
            [self removeChildByTag:SPR_TAG_LAB_START+i cleanup:YES];
        }
    }
    
    
    
    //获取软件列表
    SWList * aSWList=[SWList sharedInstance];

    
    
    int i=0;
    for( CCNode *child in [menu children] ) {
        
       
        int curIndex=mPageIndex*MAX_COLS*MAX_ROWS+i;
        if (curIndex >= [aSWList getSWCount]) {
            break;
        }
        
        SW_ITEM * item=[aSWList getItemByIndex:curIndex];
        
        ////将NSData中图象数据转换位精灵图象
        if (item.imageData == nil) {
            continue;
        }
        
        UIImage* image=[UIImage imageWithData:item.imageData];
        
        
        int oriW=image.size.width;
        int oriH=image.size.height;
        float scale=child.contentSize.width/2/oriW;
        
        //UIImage* imageSmall=[self scaleAndRotateImage:image xScale:0.5 yScale:0.5];
        UIImage* image2=[self resizeImage:image andScaleX:scale andScaleY:scale];
        NSString * index_str=[NSString stringWithFormat:@"SW_ITEM_PIC_%d",curIndex];
        CCSprite* spt=[CCSprite spriteWithCGImage:image2.CGImage key:index_str];
        
        spt.position=ccp(menu.position.x+child.position.x,menu.position.y+child.position.y);
        [self addChild:spt z:10 tag:SPR_TAG_PIC_START+i];
        
        NSString * fontName=[NSString stringWithString:@"Marker Felt"];  //@"Marker Felt"//@"ArialHebrew"
        CCLabelTTF * label=[CCLabelTTF labelWithString:item.name fontName:fontName 
                                              fontSize:spt.contentSize.width/8];
        label.position=ccp(spt.position.x, 
                           spt.position.y-spt.contentSize.height/2-label.contentSize.height/2-3);
        
        [self addChild:label z:10 tag:SPR_TAG_LAB_START+i];
        
        i++;
    }
}

-(void)menuCallback_Link:(id)sender
{
    [GameMusicSetting playButtonClickEffect];
    
    if (mPageCount == 0) {
        return;
    }
    
    int i=0;
    for( CCNode *child in [menu children] ) {
            
        if (sender == child) {
            break;
        }
        
        i++;
    }
    


    SWList * aSWList=[SWList sharedInstance];
    
    int index= mPageIndex * MAX_COUNT_PER_PAGE +i;
    if (index >= [aSWList getSWCount]) {
        return;
    }
    
    SW_ITEM * item=[aSWList getItemByIndex:index];
    
    UIApplication *application = [UIApplication sharedApplication];
    [application openURL:[NSURL URLWithString:item.url]]; 
}



-(void) upCallback: (id) sender
{
    [GameMusicSetting playButtonClickEffect];
    
	//back to game
    mPageIndex--;
    if (mPageIndex < 0) {
        mPageIndex=mPageCount-1;
    }
    
	//[self setPageIndex:mPageIndex];
    [self updateDisplay];
}


-(void) downCallback: (id) sender
{
    [GameMusicSetting playButtonClickEffect];
    
	//back to game
    mPageIndex++;
    if (mPageIndex >= mPageCount) {
        mPageIndex=0; //回到第一页
    }
    
	//[self setPageIndex:mPageIndex];
	[self updateDisplay];
}


-(void) backCallback: (id) sender
{
    [GameMusicSetting playButtonClickEffect];
    
	//back to game
	[[CCDirector sharedDirector] popScene];
	
}


- (void) dealloc
{
	[super dealloc];
}



//////////////////////////////////////////////ad begin

- (void)onEnter
{
	[super onEnter];
	
	adController = [[AdViewController alloc] initWithMasterView:[[CCDirector sharedDirector] openGLView]];
	[adController setDelegate:self];
	
}

- (void)onExit
{
	//Completely remove the controller
	[adController setDelegate:nil];
	[adController release];
	adController = nil;
	
	[super onExit];
}

- (void)adController:(AdViewController*)controller didLoadiAd:(id)iadBanner;
{
	//Do something when the ad loads, like moving objects.
    
    
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=true;
}

- (void)adController:(AdViewController*)controller didFailedToRecieveiAd:(id)iadBanner;
{
	//Do something when the ad fails to load, like moving objects.;
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=false;
}

- (void)adController:(AdViewController*)controller didLoadAdMobAd:(ADBannerView*)adMobBanner;
{
	//Do something when the ad loads, like moving objects.
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=true;
}

- (void)adController:(AdViewController*)controller didFailedToRecieveAdMobAd:(ADBannerView*)adMobBanner;
{
	//Do something when the ad fails to load, like moving objects.
    CCSprite * ad_bg=[self getChildByTag:1001];
    ad_bg.visible=false;
}

//////////////////////////////ad end

#pragma mark resize uiImage
-(UIImage*) scaleAndRotateImage:(UIImage*)photoimage
                               xScale:(CGFloat)bounds_width
                               yScale:(CGFloat)bounds_height
{
    //int kMaxResolution = 300;
    
    CGImageRef imgRef =photoimage.CGImage;
    
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);
    
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    /*if (width > kMaxResolution || height > kMaxResolution)
     {
     CGFloat ratio = width/height;
     if (ratio > 1)
     {
     bounds.size.width = kMaxResolution;
     bounds.size.height = bounds.size.width / ratio;
     }
     else
     {
     bounds.size.height = kMaxResolution;
     bounds.size.width = bounds.size.height * ratio;
     }
     }*/
    bounds.size.width = bounds_width;
    bounds.size.height = bounds_height;
    
    CGFloat scaleRatio = bounds.size.width / width;
    CGFloat scaleRatioheight = bounds.size.height / height;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
    CGFloat boundHeight;
    UIImageOrientation orient =photoimage.imageOrientation;
    switch(orient)
    {
            
        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;
            
        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;
            
        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;
            
        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
            
        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
            
        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
            
        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
            
        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid?image?orientation"];
            break;
    }
    
    UIGraphicsBeginImageContext(bounds.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft)
    {
        CGContextScaleCTM(context, -scaleRatio, scaleRatioheight);
        CGContextTranslateCTM(context, -height, 0);
    }
    else
    {
        CGContextScaleCTM(context, scaleRatio, -scaleRatioheight);
        CGContextTranslateCTM(context, 0, -height);
    }
    
    CGContextConcatCTM(context, transform);
    
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageCopy;
}


/*
 对UIImage进行缩放的函数
 */
-(UIImage *)resizeImage:(UIImage *)image andScaleX:(float)scaleX andScaleY:(float)scaleY
{
    // original
    //UIImage *image = [UIImage imageNamed:@"icon.png"];
    
    CGRect newRect;
    newRect.size.height = image.size.height*scaleY;
    newRect.size.width = image.size.width*scaleX;
    newRect.origin = (CGPoint){0.0f, 0.0f};
    UIGraphicsBeginImageContext(newRect.size);
    [image drawInRect:newRect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //使用 newImage 即可
    return newImage;
}




@end
